package cn.edu.scnu.lastandroid.logic.network

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object WeatherNetWork {
    private val placeService = ServiceCreator.create<PlaceService>()
    private val weatherService = APIServiceCreator.create(WeatherService::class.java)

    suspend fun searchPlaces(query: String) = placeService.searchPlaces(query).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(
                        RuntimeException("response body is null")
                    )
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }

    /**
     * 按照城市获取多日天气
     */
    suspend fun getDailyWeather(city: String) =
        weatherService.getDailyWeather(city).await()

    /**
     * 按照城市获取实时天气
     */
    suspend fun getRealtimeWeather(city: String) =
        weatherService.getRealTimeWeather(city).await()

    /**
     * 按照经纬度获取多日天气
     */
    suspend fun getDailyWeather(lng: String, lat: String) =
        weatherService.getDailyWeather(lng, lat).await()

    /**
     * 按照经纬度获取实时天气
     */
    suspend fun getRealtimeWeather(lng: String,lat: String) =
        weatherService.getRealTimeWeather(lng, lat).await()

    /**
     * 按照城市获取生活指数
     */
    suspend fun getLifeResponse(city: String) =
        weatherService.getLifeIndex(city).await()

    /**
     * 按照经纬度获取生活指数
     */
    suspend fun getLifeResponse(lng: String, lat: String) =
        weatherService.getLifeIndex(lng, lat).await()

    /**
     * 按照城市获取空气质量
     */
    suspend fun getAQI(city: String) =
        weatherService.getAQI(city).await()

    /**
     * 按照经纬度获取空气质量
     */
    suspend fun getAQI(lng: String, lat: String) =
        weatherService.getAQI(lng, lat).await()
}